import re
import os
import time

reg_ip = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).+?SASL LOGIN authentication')


def extract_ip_from_line(line):
    match = reg_ip.search(line)
    if match:
        return match.group(1)
    else:
        return None


def extract_ip_in_last_20_lines(log_file_name):
    # https://stackoverflow.com/questions/260273/most-efficient-way-to-search-the-last-x-lines-of-a-file
    with open(log_file_name, "r") as f:
        f.seek(0, 2)  # Seek @ EOF
        fsize = f.tell()  # Get Size
        f.seek(max(fsize - 1024, 0), 0)  # Set pos @ last n chars
        lines = f.readlines()  # Read to end

    lines = reversed(lines[-20:])  # Get last 10 lines
    for line in lines:
        found = extract_ip_from_line(line)
        # print(line)
        if found:
            return found
    return None


def watch_changes_and_get_ip(log_file_name, interval_sec=5):
    # https://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes
    cached_stamp = None
    while True:
        stamp = os.stat(log_file_name).st_mtime
        if cached_stamp != stamp:
            cached_stamp = stamp
            print(extract_ip_in_last_20_lines(log_file_name))
        time.sleep(interval_sec)


if __name__ == "__main__":
    ip = extract_ip_in_last_20_lines('mail.log')
    print(ip)
    # interval_sec=3可以不写，可选参数，默认5
    # watch_changes_and_get_ip('mail.log', interval_sec=3)
